package com.kasax.plugin.app.visitor.addLog

import com.kasax.plugin.app.LogUtils
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes


class AdddLogMethodVisitor extends MethodVisitor {
    String TAG = "AdddLogMethodVisitor"

    AdddLogMethodVisitor(MethodVisitor methodVisitor) {
        super(Opcodes.ASM7, methodVisitor)
    }

    @Override
    void visitCode() {
        super.visitCode()
        LogUtils.d(TAG, "visitCode start...")
        // 方法执行前插入
        // 相当于日志的tag
        mv.visitLdcInsn("zzg")

        mv.visitTypeInsn(Opcodes.NEW, "java/lang/StringBuilder")
        mv.visitInsn(Opcodes.DUP)

        // new StringBuilder
        mv.visitMethodInsn(
                Opcodes.INVOKESPECIAL,
                "java/lang/StringBuilder",
                "<init>",
                "()V",
                false
        )
        mv.visitLdcInsn("into ")
        mv.visitMethodInsn(
                Opcodes.INVOKEVIRTUAL,
                "java/lang/StringBuilder",
                "append",
                "(Ljava/lang/String;)Ljava/lang/StringBuilder;",
                false
        )

        mv.visitTypeInsn(Opcodes.NEW, "java/lang/Exception")
        mv.visitInsn(Opcodes.DUP)
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Exception", "<init>", "()V", false)
        mv.visitMethodInsn(
                Opcodes.INVOKEVIRTUAL,
                "java/lang/Exception",
                "getStackTrace",
                "()[Ljava/lang/StackTraceElement;",
                false
        )
        mv.visitInsn(Opcodes.ICONST_0)
        mv.visitInsn(Opcodes.AALOAD)
        mv.visitMethodInsn(
                Opcodes.INVOKEVIRTUAL,
                "java/lang/StackTraceElement",
                "getMethodName",
                "()Ljava/lang/String;",
                false
        )
        mv.visitMethodInsn(
                Opcodes.INVOKEVIRTUAL,
                "java/lang/StringBuilder",
                "append",
                "(Ljava/lang/String;)Ljava/lang/StringBuilder;",
                false
        )
        mv.visitMethodInsn(
                Opcodes.INVOKEVIRTUAL,
                "java/lang/StringBuilder",
                "toString",
                "()Ljava/lang/String;",
                false
        )
        mv.visitMethodInsn(
                Opcodes.INVOKESTATIC,
                "com/kasax/basiclib/MyLog",
                "logD",
                "(Ljava/lang/String;Ljava/lang/String;)V",
                false
        )
        LogUtils.d(TAG, "visitCode complete...")
    }

    @Override
    void visitInsn(int opcode) {
        super.visitInsn(opcode)
    }
}